import turtle

# 创建一个窗口和画笔
screen = turtle.Screen()
screen.bgcolor("white")

pen = turtle.Turtle()
pen.speed(0)
pen.penup()
pen.goto(0, -200)
pen.pendown()
pen.left(90)
pen.color("green")

# L系统参数
axiom = "F"
rules = {"F": "FF+[+F-F-F]-[-F+F+F]"}
iterations = 5
angle = 25

# 应用L系统规则生成字符串
def apply_rules(axiom, rules, iterations):
    result = axiom
    for _ in range(iterations):
        new_result = ""
        for char in result:
            if char in rules:
                new_result += rules[char]
            else:
                new_result += char
        result = new_result
    return result

# 使用L系统绘制植物
def draw_lsystem(instructions, angle, distance):
    stack = []
    for cmd in instructions:
        if cmd == 'F':
            pen.forward(distance)
        elif cmd == '+':
            pen.right(angle)
        elif cmd == '-':
            pen.left(angle)
        elif cmd == '[':
            # 保存当前位置和方向
            stack.append((pen.position(), pen.heading()))
        elif cmd == ']':
            # 恢复之前的位置和方向
            position, heading = stack.pop()
            pen.penup()
            pen.goto(position)
            pen.setheading(heading)
            pen.pendown()

# 生成并绘制L系统植物
lsystem_string = apply_rules(axiom, rules, iterations)
draw_lsystem(lsystem_string, angle, 5)

# 点击关闭窗口
screen.exitonclick()